import React, { FC, useEffect, useState } from 'react'
import { Pagination } from 'antd'
import { LIST_PAGE_SIZE } from '../../constant'
import { useSearchParams, useNavigate, useLocation } from 'react-router-dom'
import { LIST_PAGE_PARAMS_KEY, LIST_PAGE_SIZE_PARAMS_KEY } from '../../constant'
type PropsType = {
  total: number
}
const ListPage: FC<PropsType> = (props: PropsType) => {
  const [searchParams] = useSearchParams()
  const [current, setCurrent] = useState(1)
  const nav = useNavigate()
  const { pathname } = useLocation()
  const [pageSize, setPageSize] = useState(LIST_PAGE_SIZE)
  useEffect(() => {
    const page = (searchParams.get(LIST_PAGE_PARAMS_KEY) || 1) as number
    setCurrent(page)
    const pageSize = (searchParams.get(LIST_PAGE_SIZE_PARAMS_KEY) || LIST_PAGE_SIZE) as number
    setPageSize(pageSize)
  }, [searchParams])

  const onChangeHandler = (page: number, pageSize: number) => {
    searchParams.set(LIST_PAGE_SIZE_PARAMS_KEY, pageSize.toString())
    searchParams.set(LIST_PAGE_PARAMS_KEY, page.toString())

    nav({
      pathname,
      search: searchParams.toString(),
    })
  }
  const { total } = props
  return (
    <Pagination
      showSizeChanger
      current={current}
      pageSize={pageSize}
      total={total}
      onChange={onChangeHandler}
    />
  )
}
export default ListPage
